<template>
  <div class="bronze-codex-outer-container">
    <div class="bronze-codex-container">
      <div class="bronze-codex" @click="closeDropdowns" ref="bronzeCodex">
        <header>
          <button @click="goBack" class="back-button">返回</button>
          <h1>青铜图鉴</h1>
        </header>

        <div class="filter-container">
          <!-- 类别选择 -->
          <div class="category-filter">
            <button @click.stop="toggleCategories" class="category-button">
              {{ currentCategory || "请选择类别" }}
            </button>
            <!-- 类别下拉列表 -->
            <transition name="fade">
              <div v-if="showCategories" class="category-list">
                <div class="category-row">
                  <button
                    v-for="category in orderedCategories"
                    :key="category"
                    @click.stop="filterByCategory(category)"
                    :class="[
                      'category-item',
                      { active: currentCategory === category },
                    ]"
                  >
                    {{ category }}
                  </button>
                </div>
              </div>
            </transition>
          </div>

          <!-- 年代选择 -->
          <div class="era-filter">
            <button @click.stop="toggleEras" class="era-button">
              请选择年代
            </button>
            <!-- 年代下拉列表 -->
            <transition name="fade">
              <div v-if="showEras" class="era-list">
                <div class="era-row">
                  <button
                    v-for="eraOption in eras"
                    :key="eraOption"
                    @click.stop="filterByEra(eraOption)"
                    :class="['era-item', { active: currentEra === eraOption }]"
                  >
                    {{ eraOption }}
                  </button>
                </div>
              </div>
            </transition>
          </div>

          <!-- 当前选择显示 -->
          <span class="current-selection">
            {{ displayCurrentSelection }}
            <button
              v-if="currentCategory || currentEra"
              @click="resetFilters"
              class="reset-button"
            >
              重置筛选
            </button>
          </span>
        </div>

        <!-- 文物展示网格 -->
        <div class="artifacts-grid">
          <div
            v-for="artifact in artifacts"
            :key="artifact.id"
            class="artifact-card"
          >
            <div class="artifact-image">
              <img
                :src="getImageUrl(artifact.id, artifact.class)"
                :alt="artifact.name"
              />
              <!-- 收藏按钮 -->
              <button
                class="favorite-button"
                :class="{ favorited: isFavorited(artifact.id) }"
                @click.stop="toggleFavorite(artifact.id)"
                :disabled="isProcessingFavorites || !userIsLoggedIn"
                :title="
                  userIsLoggedIn
                    ? isFavorited(artifact.id)
                      ? '取消收藏'
                      : '收藏'
                    : '请登录后收藏'
                "
              >
                <i
                  :class="
                    isFavorited(artifact.id) ? 'fas fa-heart' : 'far fa-heart'
                  "
                ></i>
              </button>
            </div>
            <div class="artifact-info">
              <h3>{{ artifact.name }}</h3>
              <p><strong>年代:</strong> {{ artifact.era }}</p>
              <p>
                <strong>收藏地点:</strong>
                {{ artifact.current_location || "未知" }}
              </p>
              <p>
                <strong>挖掘地点:</strong> {{ artifact.excavation_location }}
              </p>
            </div>
          </div>
        </div>

        <!-- 分页按钮 -->
        <div class="pagination">
          <button
            @click="prevPage"
            :disabled="currentPage === 1"
            class="page-button"
          >
            上一页
          </button>
          <span>第 {{ currentPage }} 页</span>
          <button
            @click="nextPage"
            :disabled="!hasNextPage"
            class="page-button"
          >
            下一页
          </button>
        </div>

        <!-- 数据来源声明 -->
        <div class="data-sources">
          数据来源：殷周金文暨青銅器資料庫、吉林大学人工智能学院、中国出土青铜器全集等
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { BASE_URL } from "@/config.js";

export default {
  name: "BronzeCodex",
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    userIsLoggedIn() {
      return this.isLoggedIn;
    },
    displayCurrentSelection() {
      let selection = [];
      if (this.currentCategory) {
        selection.push(`类别：${this.currentCategory}`);
      }
      if (this.currentEra) {
        selection.push(`年代：${this.currentEra}`);
      }
      return selection.length > 0 ? selection.join(" | ") : "请选择筛选条件";
    },
  },
  data() {
    return {
      artifacts: [],
      showCategories: false,
      showEras: false,
      // 按照指定顺序排列类别
      orderedCategories: [
        "簋",
        "壺",
        "甗",
        "卣",
        "爵",
        "鐘",
        "觚",
        "觶",
        "鼎",
        "鬲",
        "匜",
        "尊",
      ],
      eras: ["商", "西周", "春秋", "战国"],
      classMapping: {
        gui: "簋",
        hu: "壺",
        yan: "甗",
        you: "卣",
        jue: "爵",
        zhong: "鐘",
        gu: "觚",
        zhi: "觶",
        ding: "鼎",
        li: "鬲",
        yi: "匜",
        zun: "尊",
      },
      currentPage: 1,
      pageSize: 12,
      hasNextPage: false,
      currentCategory: "簋", // 默认选择第一个类别
      currentEra: "",
      favorites: [], // 存储用户收藏的文物 ID
      isProcessingFavorites: false, // 处理收藏请求的状态
      fromSection: null,
    };
  },
  methods: {
    goBack() {
      if (this.fromSection !== null) {
        this.$router.push({
          name: "Home",
          query: { scrollToSection: this.fromSection },
        });
      } else {
        this.$router.push({ name: "Home" });
      }
    },
    toggleCategories(event) {
      event.stopPropagation();
      this.showCategories = !this.showCategories;
      if (this.showCategories) {
        this.showEras = false;
      }
    },
    toggleEras(event) {
      event.stopPropagation();
      this.showEras = !this.showEras;
      if (this.showEras) {
        this.showCategories = false;
      }
    },
    closeDropdowns() {
      this.showCategories = false;
      this.showEras = false;
    },
    filterByCategory(category) {
      this.currentCategory = category;
      this.currentPage = 1;
      this.fetchArtifacts();
      this.closeDropdowns();
    },
    filterByEra(era) {
      this.currentEra = era;
      this.currentPage = 1;
      this.fetchArtifacts();
      this.closeDropdowns();
    },
    getImageUrl(id, artifactClass) {
      const folder = Object.keys(this.classMapping).find(
        (key) => this.classMapping[key] === artifactClass
      );
      return `/images/${folder}/${id}`; // 确保 artifactId 包含正确的扩展名
    },
    async fetchArtifacts() {
      let url = `${BASE_URL}/api/artifacts?page=${this.currentPage}&pageSize=${this.pageSize}`;
      if (this.currentCategory) {
        url += `&category=${encodeURIComponent(this.currentCategory)}`;
      }
      if (this.currentEra) {
        url += `&era=${encodeURIComponent(this.currentEra)}`;
      }

      try {
        const response = await axios.get(url);
        console.log("Received data:", response.data);
        if (Array.isArray(response.data)) {
          this.artifacts = response.data;
          this.hasNextPage = response.data.length === this.pageSize;
          // 获取收藏列表
          if (this.userIsLoggedIn) {
            this.fetchFavorites();
          }
        } else {
          console.error("Unexpected data format:", response.data);
          this.artifacts = [];
          this.hasNextPage = false;
        }
      } catch (error) {
        console.error("Error fetching artifacts:", error);
        this.artifacts = [];
        this.hasNextPage = false;
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchArtifacts();
        this.scrollToTop();
      }
    },
    nextPage() {
      if (this.hasNextPage) {
        this.currentPage++;
        this.fetchArtifacts();
        this.scrollToTop();
      }
    },
    scrollToTop() {
      this.$refs.bronzeCodex.scrollIntoView({ behavior: "smooth" });
    },
    // 检查文物是否已被收藏
    isFavorited(artifactId) {
      return this.favorites.includes(artifactId);
    },
    // 切换收藏状态
    async toggleFavorite(artifactId) {
      if (!this.userIsLoggedIn) {
        alert("请先登录！");
        return;
      }

      this.isProcessingFavorites = true;
      try {
        const userId = localStorage.getItem("userId");
        if (!userId) {
          alert("请先登录！");
          this.isProcessingFavorites = false;
          return;
        }

        if (this.isFavorited(artifactId)) {
          // 已收藏，执行取消收藏
          const response = await axios.delete(
            `${BASE_URL}/api/artifacts/${artifactId}/favorite`,
            { data: { userId } }
          );

          if (response.status === 200) {
            this.favorites = this.favorites.filter((id) => id !== artifactId);
            alert("已取消收藏");
          }
        } else {
          // 未收藏，执行收藏
          const response = await axios.post(
            `${BASE_URL}/api/artifacts/${artifactId}/favorite`,
            { userId }
          );

          if (response.status === 200 || response.status === 201) {
            this.favorites.push(artifactId);
            alert("收藏成功！");
          }
        }
      } catch (error) {
        console.error("收藏操作失败:", error);
        alert("操作失败，请稍后再试！");
      } finally {
        this.isProcessingFavorites = false;
      }
    },
    // 获取用户的收藏列表
    async fetchFavorites() {
      const userId = localStorage.getItem("userId");
      if (!userId) return;
      try {
        const response = await axios.get(
          `${BASE_URL}/api/users/${userId}/artifact-favorites`
        );
        this.favorites = response.data.map((fav) => fav.artifact_id);
      } catch (error) {
        console.error("获取收藏失败:", error);
      }
    },
    // 检查用户是否已登录
    checkLoginStatus() {
      const userId = localStorage.getItem("userId");
      this.userIsLoggedIn = !!userId;
      if (this.userIsLoggedIn) {
        this.fetchFavorites();
      }
    },
    resetFilters() {
      this.currentCategory = "";
      this.currentEra = "";
      this.currentPage = 1;
      this.fetchArtifacts();
    },
  },
  watch: {
    isLoggedIn(newVal) {
      this.userIsLoggedIn = newVal;
      if (newVal) {
        this.fetchFavorites();
      } else {
        this.favorites = [];
      }
    },
  },
  mounted() {
    this.checkLoginStatus();
    this.fetchArtifacts();
    this.fromSection = this.$route.query.fromSection;
  },
};
</script>

<style scoped>
/* 整体暗淡青铜主题样式 */

.bronze-codex-outer-container {
  padding: 20px;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  background-image: url("@/assets/s2.jpg");
  background-repeat: no-repeat; /* 背景图不重复 */
  background-size: cover; /* 背景图覆盖整个区域 */
  background-position: center; /* 背景图居中 */
  background-attachment: fixed; /* 背景图固定 */
}

.bronze-codex-container {
  margin-top: 60px;
  max-width: 1200px;
  width: 95%;
  background-color: #2e2e2e; /* 深灰背景，营造暗淡效果 */
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); /* 更深的阴影 */
  z-index: 10; /* 确保它在其他元素之下 */
}

.bronze-codex {
  font-family: "SimSun", "STSong", serif;
  color: #fdf6e3; /* 淡色字体 */
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  background: linear-gradient(
    45deg,
    #5e4b3c,
    #8b4513
  ); /* 深棕色到青铜色的渐变 */
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
  position: relative; /* 保持返回按钮在头部 */
}

h1 {
  margin: 0 10px;
  color: #fdf6e3;
  font-size: 2.8em;
  text-shadow: 2px 2px 6px rgba(0, 0, 0, 0.7);
  letter-spacing: 2px;
}

.back-button {
  position: absolute;
  left: 20px;
  background-color: #8b4513; /* 深棕色 */
  color: #fdf6e3;
  border: none;
  padding: 12px 24px;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  border-radius: 25px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.back-button:hover {
  background-color: #5e4b3c; /* 更深的棕色 */
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.5);
}

.filter-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 25px;
  position: relative;
}

.category-filter,
.era-filter {
  margin: 0 10px;
  position: relative; /* 为下拉框定位提供参考 */
}

.category-button,
.era-button {
  background-color: #5e4b3c; /* 统一的暗淡棕色 */
  color: #fdf6e3;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 25px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.category-button:hover,
.era-button:hover {
  background-color: #3e2a1f; /* 更深的棕色 */
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.5);
}

.current-selection {
  position: absolute;
  right: 0;
  font-size: 1em;
  color: white; /* 金色 */
  font-weight: bold;
  background-color: rgba(212, 175, 55, 0.8); /* 半透明金色 */
  padding: 5px 10px;
  border-radius: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  gap: 10px;
}

.reset-button {
  background-color: #8b4513;
  color: #fdf6e3;
  border: none;
  padding: 5px 10px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.3s ease;
}

.reset-button:hover {
  background-color: #5e4b3c;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.category-list,
.era-list {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 100%;
  margin-top: 10px; /* 约1cm距离 */
  background: #3e2a1f; /* 深棕色背景 */
  border: 2px solid #d4af37; /* 金色边框 */
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.5);
  z-index: 100;
  min-width: 200px;
}

.category-row,
.era-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.category-item,
.era-item {
  display: inline-block;
  padding: 10px 15px;
  margin: 5px;
  background: none;
  border: 2px solid #d4af37; /* 金色边框 */
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 20px;
  color: #fdf6e3; /* 淡色字体 */
}

.category-item:hover,
.era-item:hover,
.category-item.active,
.era-item.active {
  background-color: #d4af37; /* 金色背景 */
  color: #3e2a1f; /* 深棕色字体 */
  transform: scale(1.05);
}

.artifacts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 25px;
}

.artifact-card {
  border: 3px solid #d4af37; /* 金色边框 */
  padding: 15px;
  background: #2e2e2e; /* 深灰背景 */
  border-radius: 15px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.4s ease;
  overflow: hidden;
  position: relative; /* 使收藏按钮可以绝对定位 */
}

.artifact-image {
  width: 100%;
  height: 180px;
  overflow: hidden;
  border-radius: 10px;
  position: relative;
}

.artifact-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.4s ease;
}

.artifact-card:hover .artifact-image img {
  transform: scale(1.05);
}

.artifact-info {
  padding: 15px;
  text-align: center;
}

.artifact-card h3 {
  margin-top: 15px;
  margin-bottom: 10px;
  color: #d4af37; /* 金色 */
  font-size: 1.3em;
}

.artifact-card p {
  margin: 8px 0;
  color: #ccc; /* 浅灰色 */
  font-size: 0.95em;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
}

.page-button {
  background-color: #5e4b3c; /* 暗棕色 */
  color: #fdf6e3;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 25px;
  margin: 0 15px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.page-button:hover {
  background-color: #3e2a1f; /* 更深的棕色 */
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.5);
}

.page-button:disabled {
  background-color: #555555;
  cursor: not-allowed;
}

.favorite-button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.5em;
  color: #d4af37; /* 金色 */
  transition: color 0.3s, transform 0.3s;
  position: absolute;
  top: 10px;
  right: 10px;
}

.favorite-button.favorited {
  color: #e74c3c; /* 收藏状态下的红色 */
}

.favorite-button:hover:not(:disabled) {
  transform: scale(1.2);
  color: #e74c3c;
}

.favorite-button:disabled {
  cursor: not-allowed;
  color: #888888;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 新增的数据来源样式 */
.data-sources {
  margin-top: 20px;
  text-align: center;
  font-size: 0.8em; /* 较小的字体 */
  color: #ccc; /* 淡灰色字体，低调显示 */
}
</style>
